package com.frejoys.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frejoys.api.service.ApiAppService;
import com.frejoys.common.enums.EPushType;
import com.frejoys.common.enums.EStatus;
import com.frejoys.common.enums.EStoreCodType;
import com.frejoys.common.util.CommonUtil;
import com.frejoys.common.util.SnowflakeUtil;
import com.frejoys.common.util.TimeUtil;
import com.frejoys.common.vo.common.PushVo;
import com.frejoys.common.vo.common.VoicePushVo;
import com.frejoys.dao.entity.Order;
import com.frejoys.dao.entity.VoiceMessage;
import com.frejoys.dao.mapper.VoiceMessageMapper;
import com.frejoys.service.OrderService;
import com.frejoys.service.StoreCodeService;
import com.frejoys.service.VoiceMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class VoiceMessageServiceImpl extends ServiceImpl<VoiceMessageMapper, VoiceMessage> implements VoiceMessageService {

    private final OrderService orderService;

    private final StoreCodeService storeCodeService;

    private final ApiAppService apiAppService;

    @Override
    public VoiceMessage saveInfo(Long storeCode, Long orderSn) {
        Integer nt = TimeUtil.unixTime();
        VoiceMessage v = new VoiceMessage();
        v.setMsgSn(SnowflakeUtil.appNextId());
        v.setDeviceSn(storeCode);
        v.setOrderSn(orderSn);
        v.setCreateTime(nt);
        v.setUpdateTime(nt);
        v.setStatus(EStatus.off.getValue());
        save(v);
        return v;
    }

    @Override
    public void voicePlay(Long orderSn) {

        // 获取店铺code，也是语音设备编号
        Order order = orderService.getStoreIdPriceByOrderSn(orderSn);
        if (order != null) {
            Long storeCode = storeCodeService.getCode(order.getStoreId(), EStoreCodType.offLine.getValue());
            if (storeCode != null) {
                VoiceMessage m = saveInfo(storeCode, orderSn);

                // 组装信息
                VoicePushVo vo = new VoicePushVo();
                vo.setMsgSn(m.getMsgSn());
                vo.setDeviceSn(m.getDeviceSn());
                vo.setContent("好享免排队免单到账" + CommonUtil.bigDecimalToString(order.getPrice()) + "元");

                PushVo push = new PushVo();
                push.setType(EPushType.voice.getValue());
                push.setData(JSONUtil.toJsonStr(vo));
                apiAppService.pushVoice(push);

            }
        }


    }

}
